package cn.com.kh;

import cn.com.elite.Util;
import cn.com.kh.hst.ThreeDesUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.util.MimeMessageParser;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.protocol.HTTP;

import javax.activation.DataSource;
import javax.activation.MimetypesFileTypeMap;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;


/**
 * @Title: cn.com.kh-HSTEmailSend
 * @Description:ngsapitask-hst 系统API接口开发Demo，重点关注业务逻辑部分
 * @Author: 赵杰
 * @Date 2023/2/3 14:22
 */

public class HSTEmailSend {
    private static final Log log = LogFactory.getLog(HSTEmailSend.class);

    private static String CM_ProductToken = "b4b49728-9eda-4f10-980e-da21ac4372b7";
    private static SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws Exception {

        String emlDir = "D:/匡衡/华盛通/版本发布/0112-邮件api接口/";
        //测试  /home/www/data/ngsfiles
        //生产  /nfs/ngsfiles
        String groovyemaildir = "D:/匡衡/华盛通/版本发布/0112-邮件api接口/";

        String emlFile = "7dfe7acb-dde2-4df6-9c9a-15885c94122a_1675407616104.eml";

        try (InputStream inputStream = new FileInputStream(emlDir + emlFile)) {
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);
            MimeMessage msg = new MimeMessage(session, inputStream);
            MimeMessageParser parser = new MimeMessageParser(msg).parse();
            //邮件唯一ID
            String messageId = parser.getMimeMessage().getMessageID();
            log.debug("邮件唯一ID:" + messageId);
            //发件人
            String from = parser.getFrom();
            log.debug("发件人:" + from);
            //收件人列表
            List<Address> toArray = parser.getTo();
            log.debug("收件人列表:" + toArray);
            //抄送人列表
            List<Address> ccArray = parser.getCc();
            log.debug("抄送人列表:" + ccArray);
            //密送人列表
            List<Address> bccArray = parser.getBcc();
            log.debug("密送人列表:" + bccArray);
            //邮件发送时间
            String sendDate = dateformat.format(parser.getMimeMessage().getSentDate());

            log.debug("邮件发送时间:" + sendDate);
            //邮件主题
            String subject = parser.getSubject();
            log.debug("邮件主题:" + subject);
            //获取正文
            String html = parser.getHtmlContent();
            //所有文件，包括附件和正文中的图片等文件
            List<DataSource> dataSources = parser.getAttachmentList();
            //获取不到html内容时，则获取非html文本内容
            if (html == null || html.length() == 0) {
                String plain = parser.getPlainContent();
                log.debug("获取非Html正文:" + plain);

            }
            log.debug("获取Html正文:" + html);

            //涉及邮件附件统一塞入处理，先下载到临时文件，后继会删除文件
            ArrayList fileurlarray = new ArrayList();

            for (DataSource dataSource : dataSources) {
                String name = dataSource.getName();
                InputStream is = dataSource.getInputStream();
                FileUtils.copyInputStreamToFile(is, new File(groovyemaildir + name));
                log.debug("邮件附件名称:" + name + " 路径:" + groovyemaildir + name);

                fileurlarray.add(groovyemaildir + name);
            }
            //log.debug("fileurlarray:" + fileurlarray);

            //auto 业务处理
            String client_key="40001";
            String hsNo="40001";//华盛号
            String title=subject;//邮件标题
            String content=html;//邮件内容
            String receiver="40001";//接收人(多个按,隔开） -华盛号
            String ccListStr="";//抄送人（多个按,隔开）-华盛号
            String sign_time= String.valueOf(Instant.now().getEpochSecond());//验签时间
            log.debug("解析信息-" +  "sign_time: " + sign_time);

            String token="40001";//鉴权token
            String sign="";//验签
            //String receiverValue="40001";//List<MultipartFile>	附件

            String url = getProperty.get("HSTURL");
            url = url+"/msg/email/sendemail";


            //鉴权变量
            String appid = getProperty.get("appid");
            String appsecret = getProperty.get("appsecret");

            //sign加密前后
            String signfront = "";
            String signafter = "";

            HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                {
                    put("token", token);
                    put("sign_time", sign_time);
                    put("hsNo", hsNo);
                    put("title", title);//邮件标题
                    put("content", content);//邮件内容
                    put("receiver", hsNo);//接收人(多个按,隔开） -华盛号
                    //put("ccListStr", "2");//抄送人（多个按,隔开）-华盛号
                    //put("receiverValue", "2");//附件
                }
            };

            log.debug("paramHashMap：" + paramHashMap);
            //自然排序 升序参数
            signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
            log.debug("sign加密MD5前：" + signfront);
            signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            //验权
            sign=signafter;

            ContentType contentType= ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);

            Map<String, ContentBody> reqParam = new HashMap<String, ContentBody>();
            reqParam.put("client_key", new StringBody(client_key, contentType));
            reqParam.put("hsNo", new StringBody(hsNo, contentType));
            reqParam.put("title", new StringBody(title, contentType));
            reqParam.put("content", new StringBody(content, contentType));
            reqParam.put("receiver", new StringBody(receiver, contentType));
            reqParam.put("ccListStr", new StringBody(ccListStr, contentType));
            reqParam.put("token", new StringBody(token, contentType));
            reqParam.put("sign_time", new StringBody(sign_time, contentType));
            reqParam.put("sign", new StringBody(sign, contentType));

            //处理涉及多附件的模式
            for(int i=0;i<fileurlarray.size();i++){
                // 读取文件
                String filename  = (String) fileurlarray.get(i);
                File file = new File(filename);
                String mimeType = new MimetypesFileTypeMap().getContentType(file);
                System.out.println("文件MimeType：" + mimeType);
                reqParam.put("receiverValue", new FileBody(file, mimeType));
            }

            String httpRes =HttpClientUtil.postFileMultiPart(url, reqParam);
            System.out.println("调用发送邮件结果:" + httpRes);

            for(int j=0;j<fileurlarray.size();j++){
                String deletename  = (String) fileurlarray.get(j);
                //log.debug("deletename:" + deletename );
                //删除文件
                deleteFile(deletename);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除文件
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径只有单个文件
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println(fileName + "不存在！");
            return false;
        }
    }
}
